<?php
namespace app\controller\demo;

use app\services\tools\QiniuService;

class Qiniu extends Application
{

    protected $qiniu;


    public function initialize()
    {
        /**
         * 绑定qiniu service服务类
         */
        $this->qiniu = app(QiniuService::class);
    }

    /**
     * 获取该帐号下的bucket
     */
    public function getBuckets()
    {
        dump($this->qiniu->buckets());
    }

    /**
     * 获取该bucket下所绑的域名
     */
    public function getDomains()
    {
        dump($this->qiniu->domains());
    }

    /**
     * 显示文件列表
     */
    public function getList()
    {
        dump($this->qiniu->list('test'));
    }

    /**
     * 抓取网络资料上传到bucket
     */
    public function getFetch()
    {
        $url = 'https://developer.qiniu.com/assets/logo-white-b90d685a6b146884636382426d11b7236f5f7ca1c5dfafdb6fa777a0f976fc1f.png';
        $key = 'test/'. str_random(8) . '.png';
        dump($this->qiniu->fetch($url, $key));
    }

    /**
     * 删除一个或者多个资源
     */
    public function getDelete()
    {
        $keys = [
            'test/4teVPDgH.png',
        ];
        dump($this->qiniu->delete($keys));
    }

    /**
     * 获取资源的元数据
     */
    public function getStat()
    {
        $key = 'test/upload_test.jpg';
        dump($this->qiniu->stat($key));
    }

    /**
     * 上传本地文件到bucket
     */
    public function getUpload()
    {
        //要上传文件的本地路径
        $filePath = app()->getRootPath() . 'public/image/test.jpg';
        //上传到七牛后保存的文件名
        $key = 'test/upload_test.jpg';
        if (file_exists($filePath)) {
            dd($this->qiniu->upload($filePath, $key));
        }
        return json($this->formatResult(-1, 'file no exist'));
    }

    /**
     * 上传本地文件，已存在bucket的资源替换
     */
    public function getReplace()
    {
        $filePath = app()->getRootPath() . 'public/image/test.jpg';
        $key = 'test/upload_test.jpg';

        if (file_exists($filePath)) {
            dd($this->qiniu->replace($filePath, $key));
        }
        return json($this->formatResult(-1, 'file no exist'));
    }

    /**
     * 刷新资源 url方式 dir要审请
     */
    public function getRefresh()
    {
        $key = 'test/upload_test.jpg';
        dump($this->qiniu->refresh($key));
    }
}
